package com.xyw.code.platform.webapps.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.xyw.code.common.core.entity.vo.SecurityUser;
import com.xyw.code.common.core.util.UserContextHolder;
import com.xyw.code.platform.common.entity.enums.RoleConstant;
import com.xyw.code.platform.common.entity.exception.CheckedException;
import com.xyw.code.platform.common.entity.util.XUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Classname DataScopeInterceptor
 * @Description Mybatis 拦截器 主要用于数据权限拦截
 * Created by xuyiwei on 2019/7/30.
 */
@Slf4j
@AllArgsConstructor
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Component
public class DataScopeInterceptor extends AbstractSqlParserHandler implements Interceptor {

    private final DataSource dataSource;


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        this.sqlParser(metaObject);
        // 先判断是不是SELECT操作 不是直接过滤
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        // 得到是不是select语句
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        // 执行的SQL语句
        String originalSql = boundSql.getSql();
        // SQL语句的参数
        Object parameterObject = boundSql.getParameterObject();
        //查找参数中包含DataScope类型的参数
        DataScope dataScope = findDataScopeObject(parameterObject);
        if ( dataScope == null ) {
            return invocation.proceed();
        }else{
            String scopeName = dataScope.getScopeName();
            List<Long> deptIds = dataScope.getDeptIds();
            // 优先获取赋值数据
            SecurityUser user = UserContextHolder.getInstance().getContext();
            if (user == null) {
                throw new CheckedException("auto datascope, set up security details true");
            }
            // 解析角色Id
            List<String> roleCodes = user.getAuthorities();
            if(roleCodes.size()>0){
                List<String> roleCodesin = roleCodes.stream().map(code->"'"+code+"'").collect(Collectors.toList());
                // 通过角色Id查询范围权限
                Entity query = Db.use(dataSource)
                        .query("SELECT * FROM sys_role where role_code IN (" + CollUtil.join(roleCodesin, ",") + ")")
                        .stream().min(Comparator.comparingInt(o -> o.getInt("ds_type"))).orElse(new Entity());
                // 数据库权限范围字段
                Integer dsType = query.getInt("ds_type")==null?RoleConstant.RoleDsTypeEnum.ALL.getType():query.getInt("ds_type");
                // 查询全部
                if (RoleConstant.RoleDsTypeEnum.ALL.getType() == dsType) {
                    return invocation.proceed();
                }else if(RoleConstant.RoleDsTypeEnum.THIS_LEVEL.getType() == dsType){
                    deptIds.add(user.getDeptId());
                }else if(RoleConstant.RoleDsTypeEnum.THIS_LEVEL_CHILDREN.getType() == dsType){
                    List<Entity> depts = Db.use(dataSource)
                            .query("SELECT * from sys_dept");
                    Map<Long,List<Long>> map = new HashMap<>();
                    for(Entity entity:depts){
                        Long parentId = entity.getLong("parent_id");
                        Long id = entity.getLong("id");
                        List<Long> childs = map.get(parentId);
                        if(childs==null){
                            childs = new ArrayList<>();
                        }
                        childs.add(id);
                        map.put(parentId,childs);
                    }
                    //最后遍历map 得到自己部门下面的部门id
                    List<Long> ids= XUtil.getChildsId(new ArrayList<>(),map,user.getDeptId());
                    ids.add(user.getDeptId());
                    deptIds.addAll(ids);
                }else{
                    // 除了全部 则要获取自定义 本级及其下级 查询本级
                    String dsScope = query.getStr("ds_scope");
                    if(StringUtils.isBlank(dsScope)){
                        //如果自定义 但是没有限制查询范围 则直接放行
                        return invocation.proceed();
                    }
                    List<Long> cdids = Arrays.stream(dsScope.split(","))
                            .map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()); //测点数组
                    deptIds.addAll(cdids);
                }
                String join = CollectionUtil.join(deptIds, ",");
                originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
                metaObject.setValue("delegate.boundSql.sql", originalSql);
            }
            return invocation.proceed();

        }

    }

    /**
     * 生成拦截对象的代理
     *
     * @param target 目标对象
     * @return 代理对象
     */
    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    /**
     * mybatis配置的属性
     *
     * @param properties mybatis配置的属性
     */
    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 查找参数是否包括DataScope对象
     *
     * @param parameterObj 参数列表
     * @return DataScope
     */
    private DataScope findDataScopeObject(Object parameterObj) {
        if (parameterObj instanceof DataScope) {
            return (DataScope) parameterObj;
        } else if (parameterObj instanceof Map) {
            for (Object val : ((Map<?, ?>) parameterObj).values()) {
                if (val instanceof DataScope) {
                    return (DataScope) val;
                }
            }
        }
        return null;
    }
}
